// ============================================================================
//
// Copyright (C) 2006-2007 Dengues
//
// Google Group: http://groups.google.com/group/dengues
//
// QQ Group: 24885404
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// ============================================================================
package org.dengues.ui.export;

import static org.dengues.core.export.EtlProcessScriptsManager.PATH_SEPARATOR;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.dengues.core.ExceptionOperation;
import org.dengues.core.export.EtlProcessScriptsManager;
import org.dengues.core.export.ExportFileResource;
import org.dengues.core.export.FileSystemExportScriptOperation;
import org.dengues.core.prefs.IDenguesPrefsConstant;
import org.dengues.core.warehouse.ENavNodeType;
import org.dengues.core.warehouse.IWarehouseNode;
import org.dengues.model.warehouse.ProcessType;
import org.dengues.ui.DenguesUiPlugin;
import org.dengues.ui.i18n.Messages;
import org.eclipse.jface.preference.DirectoryFieldEditor;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

/**
 * Qiang.Zhang.Adolf@gmail.com class global comment. Detailled comment <br/>
 * 
 * $Id: Dengues.epf Qiang.Zhang.Adolf@gmail.com 2008-4-9 qiang.zhang $
 * 
 */
public class ExportETLProcessPage extends WizardPage {

    private Text zText;

    private Button zButton;

    private DirectoryFieldEditor zFieldEditor;

    private Composite etlProNameComp;

    private String etlName;

    private String etlDirectory;

    private final IWarehouseNode zNode;

    private final List<ExportFileResource> zExportResList;

    /**
     * Qiang.Zhang.Adolf@gmail.com ExportETLProcessPage constructor comment.
     * 
     * @param pageName
     */
    public ExportETLProcessPage(IStructuredSelection selection) {
        super(""); //$NON-NLS-1$
        setTitle(Messages.getString("ExportETLProcessPage.title")); //$NON-NLS-1$
        setDescription(Messages.getString("ExportETLProcessPage.description")); //$NON-NLS-1$
        zNode = (IWarehouseNode) selection.getFirstElement();
        zExportResList = new ArrayList<ExportFileResource>();
        if (zNode.getNodeType().equals(ENavNodeType.ELEMENT)) {
            if (zNode.getObject() != null && zNode.getObject().getData() instanceof ProcessType) {
                ProcessType type = (ProcessType) zNode.getObject().getData();
                zExportResList.add(new ExportFileResource(type, zNode.getWarehousePath().toPortableString()));
            }
        } else {
            addChildrenNodes(zNode);
        }
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "addChildrenNodes".
     * 
     * @param node
     */
    private void addChildrenNodes(IWarehouseNode pnode) {
        List<IWarehouseNode> children = pnode.getChildren();
        for (IWarehouseNode cnode : children) {
            if (cnode.getNodeType().equals(ENavNodeType.ELEMENT)) {
                if (cnode.getObject() != null && cnode.getObject().getData() instanceof ProcessType) {
                    ProcessType type = (ProcessType) cnode.getObject().getData();
                    zExportResList.add(new ExportFileResource(type, zNode.getWarehousePath().toPortableString()));
                }
            } else {
                addChildrenNodes(cnode);
            }
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
     */
    public void createControl(Composite parent) {
        Composite container = new Composite(parent, SWT.NONE);
        GridLayout gridLayout = new GridLayout();
        gridLayout.marginHeight = 0;
        gridLayout.marginWidth = 0;
        container.setLayout(gridLayout);
        container.setLayoutData(new GridData(GridData.FILL_BOTH));
        etlProcessNameComp(container);
        zButton = new Button(container, SWT.CHECK);
        zButton.setText(Messages.getString("ExportETLProcessPage.text")); //$NON-NLS-1$
        zButton.setSelection(true);
        zButton.addSelectionListener(new SelectionAdapter() {

            /*
             * (non-Javadoc)
             * 
             * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
             */
            @Override
            public void widgetSelected(SelectionEvent e) {
                zFieldEditor.setEnabled(!zButton.getSelection(), etlProNameComp);
            }

        });
        etlProcessDirComp(container);
        setControl(container);
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "etlProcessDirComp".
     * 
     * @param container
     */
    private void etlProcessDirComp(Composite container) {
        etlProNameComp = strandComposite(container);

        String sDir = DenguesUiPlugin.getDefault().getPreferenceStore().getString(IDenguesPrefsConstant.SERVER_DIRECTORY);
        zFieldEditor = new DirectoryFieldEditor("", Messages.getString("ExportETLProcessPage.location"), etlProNameComp); //$NON-NLS-1$ //$NON-NLS-2$
        zFieldEditor.setChangeButtonText(Messages.getString("ExportETLProcessPage.browse")); //$NON-NLS-1$
        zFieldEditor.setStringValue(sDir);
        etlDirectory = sDir;
        zFieldEditor.setEnabled(false, etlProNameComp);
        zFieldEditor.getTextControl(etlProNameComp).addModifyListener(new ModifyListener() {

            /*
             * (non-Javadoc)
             * 
             * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent)
             */
            public void modifyText(ModifyEvent e) {
                etlDirectory = zFieldEditor.getStringValue();
            }
        });
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "strandComposite".
     * 
     * @param container
     */
    private Composite strandComposite(Composite container) {
        Composite etlProNameComp = new Composite(container, SWT.NONE);
        GridLayout gridLayout = new GridLayout(2, false);
        gridLayout.marginHeight = 0;
        gridLayout.marginWidth = 0;
        etlProNameComp.setLayout(gridLayout);
        etlProNameComp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        return etlProNameComp;
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "etlProcessNameComp".
     * 
     * @param container
     */
    private void etlProcessNameComp(Composite container) {
        Composite etlProNameComp = strandComposite(container);

        Label label = new Label(etlProNameComp, SWT.NONE);
        label.setText(Messages.getString("ExportETLProcessPage.label")); //$NON-NLS-1$

        zText = new Text(etlProNameComp, SWT.BORDER);
        zText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        zText.setText(zNode.getLabel().toLowerCase());
        zText.addModifyListener(new ModifyListener() {

            /*
             * (non-Javadoc)
             * 
             * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent)
             */
            public void modifyText(ModifyEvent e) {
                etlName = zText.getText();
            }
        });
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "finish".
     */
    public boolean finish() {
        if (!zButton.getSelection()) {
            DenguesUiPlugin.getDefault().getPreferenceStore().setValue(IDenguesPrefsConstant.SERVER_DIRECTORY,
                    zFieldEditor.getStringValue());
        }

        EtlProcessScriptsManager manager = new EtlProcessScriptsManager();
        boolean ok = false;
        String destinationPath = zFieldEditor.getStringValue() + PATH_SEPARATOR + zText.getText();
        FileSystemExportScriptOperation operation = new FileSystemExportScriptOperation(zExportResList, destinationPath);
        try {
            getContainer().run(true, true, operation);
            ok = true;
        } catch (InvocationTargetException e) {
            ExceptionOperation.operate(e);
        } catch (InterruptedException e) {
            ExceptionOperation.operate(e);
        }
        // path can like name/name
        manager.deleteTempFiles();

        return ok;
    }

    /**
     * Getter for etlName.
     * 
     * @return the etlName
     */
    public String getEtlName() {
        return this.etlName;
    }

    /**
     * Getter for etlDirectory.
     * 
     * @return the etlDirectory
     */
    public String getEtlDirectory() {
        return this.etlDirectory;
    }
}
